import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createStorage } from "@/utils/storage";
import { getSystemInfoSync } from "@tarojs/taro";

type ThemeType = "light" | "dark" | "pink";

// 获取系统主题
const getSystemTheme = (): ThemeType => {
  try {
    const { theme } = getSystemInfoSync();
    return theme === "dark" ? "dark" : "light";
  } catch (error) {
    console.error("获取系统主题失败:", error);
    return "light";
  }
};

interface ThemeState {
  currentTheme: ThemeType;
  changeTheme: (theme: ThemeType) => void;
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set) => ({
      currentTheme: getSystemTheme(),
      changeTheme: (theme: ThemeType) => {
        set({ currentTheme: theme });
      },
    }),
    {
      name: "theme",
      storage: createJSONStorage(() => createStorage() as any),
    }
  )
);
